﻿package kliment.utils {
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import kliment.math.Calc;
	
	/**
	 * ...
	 * @author	Kliment
	 * @version	1.0.5
	 */
	public class Transformation {
		
		public static function putInSpace(target:Object, width:Number, height:Number, crop:Boolean = true, centred:Boolean = true):Rectangle {				
			var x_ratio:Number = width / target.width;
			var y_ratio:Number = height / target.height;
			var ratio:Number = 0;
			if (crop)
				ratio = Math.max(x_ratio, y_ratio);
			else 
				ratio = Math.min(x_ratio, y_ratio);
			var use_ratio:Boolean = x_ratio == ratio? true : false;
			var new_width:Number = use_ratio? width : (target.width * ratio);
			var new_height:Number = !use_ratio? height : (target.height * ratio);
			var new_x:Number = use_ratio? 0 : Calc.half(width - new_width);
			var new_y:Number = !use_ratio? 0 : Calc.half(height - new_height);
			
			if (crop) {
				return new Rectangle(new_x, new_y, new_width, new_height);
			} else if (!centred) {
				return new Rectangle(0, 0, new_width, new_height);
			} else {
				return new Rectangle(new_x, new_y, new_width, new_height);
			}
		}
		
		static public function fixInSpace(target:Object, space:Object):Point {
			var dragRectangle:Rectangle = getDragRectangle(target, space);
			var margen_x:Number = dragRectangle.x;
			var margen_y:Number = dragRectangle.y;
			var position:Point = new Point(target.x, target.y);
			
			if (target.width > space.width) {
				position.x = Calc.inInterval(margen_x, space.x, position.x);
			} else {
				position.x = Calc.inInterval(space.x, margen_x, position.x);
			}
			if (target.height > space.height) {
				position.y = Calc.inInterval(margen_y, space.y, position.y);
			} else {
				position.y = Calc.inInterval(space.y, margen_y, position.y);
			}
			return position;
		}
		
		static public function getDragRectangle(target:Object, space:Object):Rectangle {
			var _left:Number = space.width - target.width + space.x;
			var _top:Number = space.height - target.height + space.y;
			return new Rectangle(_left, _top, space.x, space.y);
		}
		
		static public function to(target:Object, from:Object):void {
			target.x = from.x;
			target.y = from.y;
			target.width = from.width;
			target.height = from.height;
		}
		
		static public function roundRecatangle(value:Rectangle, funct:Function = null):Rectangle {
			if (funct == null)
				funct = Math.round;
			value.x = funct(value.x);
			value.y = funct(value.y);
			value.width = funct(value.width);
			value.height = funct(value.height);
			return value;
		}
	}

}